/**
 * 2017，thor.com，all rights reserved。
 * 
 * Project：		palmmall-core
 * Filename：	DailyPassengerFlowReportHqlBuilder.java
 * Created：		2017年4月27日
 * Creator：		wolv
 */
package com.thor.palmmall.dao.rpt.vehicleflow;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.thor.commons.util.StringUtil;
import com.thor.palmmall.api.rpt.vehicleflow.DailyVehicleFlowReportParam;

/**
 * @author wolv
 *
 */
public class DailyVehicleFlowReportHqlBuilder {

  public Query build(DailyVehicleFlowReportParam param) {
    StringBuffer sb = new StringBuffer();

    // select
    sb.append("select ");
    if (StringUtil.isNullOrBlank(param.getDimensionField()) == false)
      sb.append(param.getDimensionField() + ",");
    else
      sb.append("'-',");
    sb.append(" sum(" + param.getAggregationValueField() + ")");

    // from
    sb.append(" from " + PDailyVehicleFlow.class.getName());

    // where
    sb.append(" where 1=1 ");
    if (StringUtil.isNullOrBlank(param.getStoreId()) == false)
      sb.append(" and storeId = :storeId");
    if (param.getDate() != null)
      sb.append(" and date = :date");
    if (param.getBeginDate() != null)
      sb.append(" and date >= :beginDate");
    if (param.getEndDate() != null)
      sb.append(" and date <= :endDate");

    // group by
    if (StringUtil.isNullOrBlank(param.getDimensionField()) == false)
      sb.append(" group by " + param.getDimensionField());
    else
      sb.append(" group by '-'");

    Query query = em.createQuery(sb.toString());
    if (StringUtil.isNullOrBlank(param.getStoreId()) == false)
      query.setParameter("storeId", param.getStoreId());
    if (param.getDate() != null)
      query.setParameter("date", param.getDate());
    if (param.getBeginDate() != null)
      query.setParameter("beginDate", param.getBeginDate());
    if (param.getEndDate() != null)
      query.setParameter("endDate", param.getEndDate());

    return query;
  }

  public static DailyVehicleFlowReportHqlBuilder getInstance() {
    if (instance == null)
      instance = new DailyVehicleFlowReportHqlBuilder();
    return instance;
  }

  private static DailyVehicleFlowReportHqlBuilder instance;

  private DailyVehicleFlowReportHqlBuilder() {
  }

  @PersistenceContext(unitName = "${thor-webui-core.persistent-unit}")
  protected EntityManager em;
}
